/**
 * 
 *   @author   周建建
 *   start_time    2020-4-21
 * 
 */

! function($wx, ...$list) {
  /**
   *   @method
   *   @param {Array}  arrays
   *   arrays  分别为: [路由地址，参数，请求方式,如需回调请传函数]
   */
  $wx.$ajax = (...arrays) => {
    let openid = null,
      nums = 0;
    $list[0].edit ? '' : arrays = [];
    return new Promise(
      (resolve, reject) => {
        let call_fn = (id) => {
          wx.request({
            url: wx.$config.serverAddress + arrays[0],
            data: JSON.stringify({
              token: wx.getStorageSync('token') || '',
              data: arrays[1] || {}
            }),
            dataType: 'json',
            method: arrays[2].toUpperCase() || 'POST',
            header: typeof arrays[3] == "object" ? arrays[3] : {
              'content-type': 'application/x-www-form-urlencoded',
            },
            success: res => {
              resolve(res)
              typeof arrays[3] == "function" ? arrays(res) : null
            },
            fail: err => {
              reject(err)
            },
            complete: all => {
              wx.hideLoading();
              wx.hideToast()
              wx.hideNavigationBarLoading();
              console.log("进入返回值",all)
              if(all.data.code==400){
                wx.setStorageSync('token', '');
                wx.navigateTo({
                  url: '/pages/login/login',
                })
              }
              if (all.statusCode != 200) {
                wx.reLaunch({
                  url: '/pages/error/error',
                })
              } else {
                reject(all)
              }
            }
          })
        }
        call_fn(openid)
      }
    )
  }
  /**
   *   @method
   *   @param {Array}  arrays
   *   arrays  分别为: [字段名，0升序  1降序  【字段比大小】]
   */
  $wx.$sort = (...arrays) => {
    return function(a, b) {
      var value1 = a[arrays[0]];
      var value2 = b[arrays[0]];
      if (arrays[1] == 1) {
        return value2 - value1;
      } else {
        return value1 - value2;
      }
    }
  }
  /**
   *   @method
   *   @param {Array}  arrays
   *   arrays  分别为: [数组 [{}]，字段名称,0升序  1降序  【字段比大小】]
   */
  $wx.$sortTime = (...arrays) => {
    arrays[0].sort(function(a, b) {
      if (arrays[2] == 1) {
        return Date.parse(a[arrays[1]]) - Date.parse(b[arrays[1]]); //时间正序
      } else {
        return Date.parse(b[arrays[1]]) - Date.parse(a[arrays[1]])
      }
    });
    return arrays[0]
  }
  /**
   *   @method
   *   @param {Array}  arrays
   *   arrays  分别为: [数组 [{}]，字段名称]
   */
  $wx.$Distinct = (...arrays) => {
    var hash = {};
    return arrays[0].reduce(function(item, next) {
      hash[next[arrays[1]]] ? '' : hash[next[arrays[1]]] = true && item.push(next);
      return item;
    }, []);
  }
  /**
   *   @method
   *   缓存手机设备信息
   *   手机高度、宽度、iphonex~苹果手机 特定高度问题
   */
  $wx.$facility = () => {
    let set_s = wx.setStorageSync;
    wx.getSystemInfo({
      success: function(res) {
        let totalTopHeight = 68
        if (res.model.indexOf('iPhone X') !== -1) {
          totalTopHeight = 88
        } else if (res.model.indexOf('iPhone') !== -1) {
          totalTopHeight = 64
        }
        set_s('statusBarHeight', res.statusBarHeight);
        set_s('titleBarHeight', totalTopHeight - res.statusBarHeight);
        set_s("phoneW", res.screenWidth);
        set_s("phoneH", res.screenHeight);
        set_s('SystemInfo', res)
        $wx.phoneH = res.screenHeight || 0;
        $wx.phoneW = res.screenWidth || 0;
      },
      failure() {
        set_s('statusBarHeight', 0)
        set_s('titleBarHeight', 0)
      }
    })
  }


  /**
   *  @method
   *  @param {String}  title
   *  @param  {Number}  time
   *  弹框提示
   * 
   */
  $wx.$title = (title, time) => {
    wx.showToast({
      title: title,
      icon: 'none',
      duration: time || 1000
    })
  }

  /**
   *  @method
   *  @param  {String}  url
   *  @param  {Array}  urlList
   *  图片阅览
   * 
   */
  $wx.$imgRead = (url, urlList) => {
    wx.previewImage({
      current: url, // 当前显示图片的http链接
      urls: urlList ? urlList : [url] // 需要预览的图片http链接列表
    })
  }

  /**
   *  @method
   *  @param  {String}  title
   *  设置字体
   * 
   */
  $wx.$setTop = (title) => {
    wx.setNavigationBarTitle({
      title: title
    })
  }


  /**
   *  @method
   *  @param  {String}  fc   
   * @param   {String}  bc
   *  设置顶部背景颜色
   * 
   */
  $wx.$setTopBk = (fc, bc) => {
    wx.setNavigationBarColor({
      frontColor: fc || '#000000',
      backgroundColor: bc || '#ffffff',
      animation: {
        duration: 400,
        timingFunc: 'easeIn'
      }
    })
  }


  /**
   *  @method
   *  @param   {Number}  num
   *  @param   {Number}  time
   *  设置页面滚动的位置
   * 
   */
  $wx.$scrollTop = (num, time) => {
    wx.pageScrollTo({
      scrollTop: num || 0,
      duration: time || 300
    })
  }

  /**
   *  @method
   *  @param   {Array}  arr
   *  @param   {String}  key
   *  去重  传入(数组, 去重字段名)
   * 
   */
  $wx.$unique = (arr, key) => {
    const res = new Map();
    return arr.filter((a) => !res.has(a[key]) && res.set(a[key], 1))
  }

  /**
   * 
   *  时间戳转时间
   * 
   */

  $wx.timestamp=(stamp, type)=>{
    // 判断是不是13位的时间戳格式
    if (stamp.length < 13) {
      stamp = stamp * 1000
    } else {
      stamp = stamp
    }
    let date = new Date(Number(stamp)),
      year = date.getFullYear(),
      month = date.getMonth() + 1 > 9 ? date.getMonth() + 1 : '0' + (date.getMonth() + 1),
      day = date.getDate() > 9 ? date.getDate() : '0' + date.getDate(),
      hour = date.getHours() > 9 ? date.getHours() : '0' + date.getHours(),
      minute = date.getMinutes() > 9 ? date.getMinutes() : '0' + date.getMinutes(),
      second = date.getSeconds() > 9 ? date.getSeconds() : '0' + date.getSeconds();
      
      if(type === 'year'){
        return year
      }else if(type === 'month'){
        return year + '-' + month
      }else if(type === 'day'){
        return year + '-' + month + '-' + day
      }else{
        return year + '-' + month + '-' + day + ' ' + hour + ':' + minute + ':' + second
      }
  }

  /**
   * 
   * 
   *  公共上传处理
   *  @param   {Number}  count
   *  
   * 
   */
  $wx.$uploadFile=(count)=>{
      wx.chooseImage({
        count: 1,
        sizeType: ['original', 'compressed'],
        sourceType: ['album', 'camera'],
        success(res) {
          // tempFilePath可以作为img标签的src属性显示图片
          const tempFilePaths = res.tempFilePaths
        }
      })

  }


  $wx.$uploadFile = (count,callBlack) =>{
    let sequence=(i)=>{
      return new Promise(
        (resolve, reject) => {
          const uploadTask = wx.uploadFile({
            url: wx.$config.uploadFile, 
            filePath: i,
            name: 'file',
            formData: {
              'token': wx.getStorageSync("token")
            },
            success(res) {
              if (res.errMsg == "uploadFile:ok") {
                const data = res.data
                resolve(JSON.parse(data).data)
              }
            }, fail: Error => {
              console.log(Error, '错误')
            }
          })
          uploadTask.onProgressUpdate((res) => {
          })
        }
      )
    }
    wx.chooseImage({
      count: count,
      sizeType: ['original', 'compressed'],
      sourceType: ['album', 'camera'],
      success: res => {
        let tempFilePaths = res.tempFilePaths
        let promised = []
        for (let i = 0; i < tempFilePaths.length; i++) {
          promised[i] = sequence(tempFilePaths[i])
        }
        Promise.all(promised).then(r => {
          callBlack(r)
        })
        .catch(err => {
          console.log(err)
        })
      }
    })
  }

  $wx.computeHeight = (className,  cb) => {
        wx.getSystemInfo({
            complete:  (res)  =>  {
                const query  =  wx.createSelectorQuery()
                query.select(className).boundingClientRect()
                query.selectViewport().scrollOffset()
                query.exec(function  (r)  {
                    cb(res.windowHeight  -  r[0].height)
                })
            },
        })
    }
  // 验证手机号码
  $wx.isMobile=(str)=>{
    return /^(13|14|15|16|17|18|19)\d{9}$/i.test(str);
  }


}(typeof wx == "object" ? wx : new Object(),
  wx.$config,

)